package edu.office.applicationRepository;

import edu.office.entities.*;
import edu.office.sessionRepository.CommonModelSSRep;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;

/**
 *
 * @author haogs
 */
@Named
@ApplicationScoped
public class MyPublishedAll extends CommonModelSSRep<Knowledge> implements java.io.Serializable {

    @Inject
     ReexaminationRepository reexaminationRepository;
    @Inject
     KnowledgeRepository knowledgeController;
    @Inject
     SchoolRepository schoolRepository;
          @Inject
       SubjectRepository subjectRepository;
    @Inject
     MajorRepository majorController;
    @Inject
    QuestionRepository questionRepository;
    @Inject
    StudentRepository studentRepository;
    //private int type = 0;//0表示按照录入者所在班级查询，1表示按照录入的课程查询 
    // private List<StudentPublished> studentAllPublished = new LinkedList<>();
    protected Knowledge current;

    //=================发布者的知识点和习题汇集==============begin===================

    private HashMap<Student, List<List<Integer>>> collectData(School school, Subject subject) {
        HashMap<Student, List<List<Integer>>> studentPublisthHashMap=new HashMap<>();
        //准备相关变量
            HashMap<Student, List<Integer>> studentKnowledgeMap = new HashMap<>(), studentQuestionMap = new HashMap<>();
            //上面这两个Map分别存储知识点与习题，下面进行填充
            List<Reexamination> allReexaminations;
            //通过学生名单获得每个学生录入的知识点与习题
            StringBuilder sb = new StringBuilder();

                sb.append("studentid in (");
                List<Student> studentSet = studentRepository.list("SCHOOL_ID",school.getID());
                for (Student student : studentSet) {
                    sb.append(student.getId()).append(",");
                }
                String whereCond = sb.toString();
                if (whereCond.length() > 15) {//已经有了studentid in (
                    whereCond = whereCond.substring(0, whereCond.length() - 1);
                    whereCond += ") order by studentid";
                    allReexaminations = reexaminationRepository.list("select * from Reexamination where " + whereCond);
                } else {//没有学生
                    allReexaminations = new LinkedList<>();
                }
                //上面这两个Map分别存储知识点与习题，下面进行填充
                for (Reexamination reexamination : allReexaminations) {
                    List<Knowledge> lk= knowledgeController.list("id",reexamination.getKNOWLEDGEID());
                    Knowledge knowledge=null;
                    if(!lk.isEmpty()) knowledge=lk.get(0);
                    List<Student> ls=studentRepository.list("id",reexamination.getSTUDENTID());
                    Student student=null;
                    if(!ls.isEmpty()) student=ls.get(0);
                    List<Question> lq=questionRepository.list("id",reexamination.getQUESTIONID());
                    Question question=null;
                    if(!lq.isEmpty()) question=lq.get(0);
                    if (knowledge != null) {//是知识点
                        if (studentKnowledgeMap.get(student) == null) {
                            studentKnowledgeMap.put(student, new LinkedList());
                        }
                        if (subject!= null ) {
                            if (Objects.equals(knowledge.getSUBJECT_ID(), subject.getID())) {
                                studentKnowledgeMap.get(student).add(knowledge.getID());
                            }
                        } else {//没有选择课程，则可以无条件填加
                            studentKnowledgeMap.get(student).add(knowledge.getID());
                        }
                    } else if (question != null) {//是习题
                        if (studentQuestionMap.get(student) == null) {
                            studentQuestionMap.put(student, new LinkedList());
                        }
                        if (subject != null ) {
                            if (Objects.equals(knowledge.getSUBJECT_ID(), subject.getID())) {
                                studentQuestionMap.get(student).add(reexamination.getQUESTIONID());
                            }
                        } else {//没有选择课程，则可以无条件填加
                            studentQuestionMap.get(student).add(reexamination.getQUESTIONID());
                        }
                    }
                }


            //HashMap填充完毕，下面开始完善studentPublished
            for (Entry<Student, List<Integer>> entry : studentKnowledgeMap.entrySet()) {
                //刚开始，map中一定不存在这个学生信息，所以要put
                studentPublisthHashMap.put(entry.getKey(), new LinkedList<>());
                studentPublisthHashMap.get(entry.getKey()).add(entry.getValue());
                if (studentQuestionMap.get(entry.getKey()) != null) {
                    studentPublisthHashMap.get(entry.getKey()).add(studentQuestionMap.get(entry.getKey()));
                    //已经添加进去了，所以删除，剩下的是还没添加进去的
                    studentQuestionMap.remove(entry.getKey());
                } else {
                    //这个学生没录入习题
                    studentPublisthHashMap.get(entry.getKey()).add(new LinkedList<>());
                }
            }
            //接着对剩下的questionMap进行处理,剩下的一定尚未包含在studentAllPublished中，即未录入知识点，只录入了习题
            for (Entry<Student, List<Integer>> entry : studentQuestionMap.entrySet()) {
                studentPublisthHashMap.put(entry.getKey(), new LinkedList<>());
                studentPublisthHashMap.get(entry.getKey()).add(new LinkedList<>());//对应的知识点为空表
                studentPublisthHashMap.get(entry.getKey()).add(studentQuestionMap.get(entry.getKey()));
            }
            return studentPublisthHashMap;
    }

    //覆盖父类的这个方法的目的，是使得继承父类的方法可以直接使用
    //=================发布者的知识点汇集==============begin===================
    public List<Question> collectMine4Question(TeacherAdmin teacherAdmin) {
        return collectData4Question(teacherAdmin, null);
    }

    public List<Question> collectMine4Question(Student student) {
        return collectData4Question(null, student);
    }

    private List<Question> collectData4Question(TeacherAdmin teacherAdmin, Student student) {
        String whereString = "";
        if (null != student) {
            //只有学生登录
            whereString = " where  studentid=" +student.getId();
        } else if (null != teacherAdmin) {
            //只有老师登录
            whereString = " where  teacherid=" + teacherAdmin.getID();
        }
        List<Question> myPublishedQuestionCollection;
        List<Reexamination> allReexaminations = reexaminationRepository.list("select * from Reexamination " + whereString + " and questionId  is not null and iscreate=true");
        if (!allReexaminations.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            allReexaminations.forEach(reex -> sb.append(reex.getQUESTIONID()).append(","));
            String where = sb.toString();
            where = where.substring(0, where.length() - 1);
            myPublishedQuestionCollection = questionRepository.list("select * from question where id in (" + where + ")");
        } else {
            myPublishedQuestionCollection = new LinkedList<>();
        }
        return myPublishedQuestionCollection;

    }

    private List<Knowledge>  collectData4Knowledge(Student student, TeacherAdmin teacherAdmin) {
        List<Knowledge> myPublishedKnowledges = new LinkedList<>();
        StringBuilder whereString = new StringBuilder();
        if (null != student) {
            whereString.append("  where studentid=").append(student.getId());
        } else if (null != teacherAdmin) {
            whereString.append(" where  teacherid=").append(teacherAdmin.getID());
        }
        List<Reexamination> allReexaminations = reexaminationRepository.list("select * from Reexamination " + whereString.toString() + " and knowledgeId  is not null and isCreate=true");
        if (allReexaminations.size() > 0) {
            StringBuilder sb = new StringBuilder();
            allReexaminations.forEach(reex -> {
                Knowledge k= knowledgeController.find("ID",reex.getKNOWLEDGEID()).firstResult();
                sb.append(k.getID()).append(",");
            });
            String where = sb.toString();
            where = where.substring(0, where.length() - 1);
            myPublishedKnowledges = knowledgeController.list("select * from Knowledge where id in(" + where + ")");
        } else {
            myPublishedKnowledges = new LinkedList<>();
        }
        return myPublishedKnowledges;
    }
}
